<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Member as MemberModel;
use app\admin\model\Module as ModuleModel;
use util\Tree;
use think\facade\Db;

/**
 * 会员用户管理控制器
 * @package app\user\admin
 */
class Member extends Admin
{
    /**
     * 用户首页
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();

        // 数据列表
        $data_list = MemberModel::where($map)->order('sort, id desc')->paginate(config('paginate'));

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('用户管理') // 设置页面标题
            ->setTableName('user_member') // 设置数据表名
            ->setSearch(['id' => 'ID', 'nickname' => '昵称', 'mobile' => '手机号']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['nickname', '昵称'],
                ['role', '来源', 'status', '', MemberModel::role()],
                ['openid', '微信OPENID'],
                ['realname', '姓名'],
                ['mobile', '手机号'],
                ['create_time', '创建时间', 'datetime'],
				['last_login_ip', '最后登录Ip', 'callback', function($value){return long2ip($value);}],
				['last_login_time', '最后登录时间',  'datetime'],
				//['branch_bind', '内部人员', 'switch'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('enable,disable,delete') // 批量添加顶部按钮
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	/**
	 * 实名认证
	 * @author PaulXun <paulxun@qq.com>
	 * @return mixed
	 * @throws \think\Exception
	 * @throws \think\exception\DbException
	 */
	public function auth()
	{
	    cookie('__forward__', $_SERVER['REQUEST_URI']);
	
	    // 获取查询条件
	    $map = $this->getMap();
		
		// 待认证信息
		$map[] = ['realname', '<>', ''];
		$map[] = ['mobile', '<>', ''];
		$map[] = ['idcard', '<>', ''];
	    // 数据列表
	    $data_list = MemberModel::where($map)->order('auth, id desc')->paginate(config('paginate'));
	
	    // 认证按钮
	    $btn_access = [
	        'title' => '更改认证',
	        'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default ajax-get',
	        'href'  => url('audit', ['ids' => '__id__'])
	    ];
		// 批量认证按钮
		$btn_audit = [
		    'title' => '认证',
		    'icon'  => 'fa fa-fw fa-key',
		    'class' => 'btn btn-primary ajax-post',
		    'href'  => url('audit', ['type' => 'auth'])
		];
		// 批量认证按钮
		$btn_noaudit = [
		    'title' => '解除认证',
		    'icon'  => 'fa fa-fw fa-key',
		    'class' => 'btn btn-warning ajax-post confirm',
		    'href'  => url('audit', ['type' => 'noauth'])
		];
	    // 使用ZBuilder快速创建数据表格
	    return ZBuilder::make('table')
	        ->setPageTitle('用户管理') // 设置页面标题
	        ->setTableName('user_member') // 设置数据表名
	        ->setSearch(['id' => 'ID', 'nickname' => '昵称',  'realname' => '姓名', 'mobile' => '手机号']) // 设置搜索参数
	        ->addColumns([ // 批量添加列
	            ['id', 'ID'],
	            ['nickname', '昵称'],
	            ['realname', '姓名'],
				['idcard', '身份证号'],
	            ['mobile', '手机号'],
				['openid', '微信OPENID'],
	            ['pid', '推荐人ID'],
				['last_login_ip', '最后登录Ip', 'callback', function($value){return long2ip($value);}],
				['last_login_time', '最后登录时间',  'datetime'],
	            ['auth', '认证状态', 'yesno'],
	            ['right_button', '操作', 'btn']
	        ])
			->addTopButton('custom', $btn_audit) // 添加批量认证按钮
			->addTopButton('custom', $btn_noaudit) // 添加批量认证按钮
	        // ->addTopButtons('auth,disable,delete') // 批量添加顶部按钮
	        ->addRightButton('custom', $btn_access) // 添加授权按钮
	        ->addRightButtons('edit') // 批量添加右侧按钮
			->addFilter('auth', ['未认证', '已认证'])
	        ->setRowList($data_list) // 设置表格数据
	        ->fetch(); // 渲染页面
	}
    /**
     * 编辑
     * @param null $id 用户id
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Member.update');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
			
			// if (strripos($data['avatar_img'],'http') != 0){
			// 	$data['avatar_img'] = get_file_path($data['avatar_img'], 'full');
			// }
			
            // 如果没有填写密码，则不更新密码
            // if ($data['password'] == '') {
            //     unset($data['password']);
            // }

            if (MemberModel::update($data)) {
                $user = MemberModel::find($data['id']);
                // 记录行为
                action_log('member_edit', 'user_member', $user['id'], UID, $user['nickname']);
                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = MemberModel::where('id', $id)->find();

        // 角色列表
        $role_list = MemberModel::role();

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['text', 'nickname', '昵称', '可以是中文'],
				['text', 'realname', '姓名'],
				['text', 'mobile', '手机号'],
                ['select', 'role', '分组', '', $role_list],
                ['text', 'idcard', '身份证号', ''],
				['radio', 'auth', '认证状态', '', ['未认证', '认证']],
                //['password', 'password', '密码', '必填，6-20位'],
                ['gallery', 'avatar_img', '头像'],
                ['radio', 'status', '用户状态', '', ['禁用', '启用']]
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 授权
     * @param string $module 模块名
     * @param int $ids 用户id
     * @param string $tab 分组tab
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function audit($ids = [], $type= false)
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;
		foreach ($ids as $id) {
			$member = MemberModel::find($id);
			switch ($type) {
				case 'auth' :
				if ($member['auth'] == 0) {
					$member->auth = 1;
					$member->save();
				}
				break;
				case 'noauth' :
				if ($member['auth'] == 1) {
					$member->auth = 0;
					$member->save();
				}
				break;
				default:
				if ($member['auth'] == 1) {
					$member->auth = 0;
				} else {
					$member->auth = 1;
				}
				$member->save();
			}
			cache('vip_childs_'.$id, null); //清除缓存
		}
		$this->success('认证状态更改成功');
    }

    /**
     * 构建jstree代码
     * @param array $nodes 节点
     * @param array $curr_access 当前授权信息
     * @param array $user_access 用户授权信息
     * @author PaulXun <paulxun@qq.com>
     * @return string
     */
    private function buildJsTree($nodes = [], $curr_access = [], $user_access = [])
    {
        $result = '';
        if (!empty($nodes)) {
            $option = [
                'opened'   => true,
                'selected' => false
            ];
            foreach ($nodes as $node) {
                $key = $curr_access['group'].'|'.$node[$curr_access['primary_key']];
                $option['selected'] = isset($user_access[$key]) ? true : false;
                if (isset($node['child'])) {
                    $curr_access_child = isset($curr_access['child']) ? $curr_access['child'] : $curr_access;
                    $result .= '<li id="'.$key.'" data-jstree=\''.json_encode($option).'\'>'.$node[$curr_access['node_name']].$this->buildJsTree($node['child'], $curr_access_child, $user_access).'</li>';
                } else {
                    $result .= '<li id="'.$key.'" data-jstree=\''.json_encode($option).'\'>'.$node[$curr_access['node_name']].'</li>';
                }
            }
        }

        return '<ul>'.$result.'</ul>';
    }

    /**
     * 删除用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($ids = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($ids = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($ids = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置用户状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        switch ($type) {
            case 'enable':
                if (false === MemberModel::where('id', 'in', $ids)->update(['status' => 1])) {
                    $this->error('启用失败');
                }
                break;
            case 'disable':
                if (false === MemberModel::where('id', 'in', $ids)->update(['status' => 0])) {
                    $this->error('禁用失败');
                }
                break;
            case 'delete':
                if (false === MemberModel::where('id', 'in', $ids)->delete()) {
                    $this->error('删除失败');
                }
                break;
            default:
                $this->error('非法操作');
        }

        action_log('member_'.$type, 'user_member', '', UID);

        $this->success('操作成功');
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');

        $config  = MemberModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $config . ')，新值：(' . $value . ')';
        return parent::quickEdit(['member_edit', 'user_member', $id, UID, $details]);
    }
}
